import React, { useState } from 'react';
import {
    Card,
    Form,
    Input,
    Button,
    Space,
    Typography,
    Checkbox,
    Divider
} from 'antd';
import {
    UserOutlined,
    LockOutlined,
    EyeInvisibleOutlined,
    EyeTwoTone,
    GithubOutlined,
    GoogleOutlined,
    WechatOutlined
} from '@ant-design/icons';
import { useNavigate, useLocation } from 'react-router-dom';
import { useThemeConfig } from '../contexts/ThemeConfigContext';
import { useAuth } from '../contexts/AuthContext';
import { useMessage } from '../contexts/MessageContext';

const { Title, Text, Link } = Typography;

const Login = () => {
    const navigate = useNavigate();
    const location = useLocation();
    const { isDark } = useThemeConfig();
    const { login, isAuthenticated, getSavedCredentials } = useAuth();
    const [loading, setLoading] = useState(false);
    const [form] = Form.useForm();
    const { showMessage } = useMessage(); // 使用 MessageContext

    // 登录页面不再需要处理已登录用户的重定向，这由RouteGuard处理

    // 页面加载时填入保存的登录信息
    React.useEffect(() => {
        const savedCredentials = getSavedCredentials();
        if (savedCredentials.username) {
            form.setFieldsValue(savedCredentials);
        }
    }, [form, getSavedCredentials]);

    // 默认账号信息
    const DEFAULT_CREDENTIALS = [
        {
            username: 'sjly',
            password: 'sjlyadmin'
        },
        {
            username: 'demo',
            password: 'demo123'
        }
    ];

    // 处理登录
    const handleLogin = async (values) => {
        setLoading(true);
        try {
            // 模拟登录API调用
            await new Promise(resolve => setTimeout(resolve, 1500));

            // 验证登录凭据
            const validUser = DEFAULT_CREDENTIALS.find(cred =>
                cred.username === values.username && cred.password === values.password
            );

            if (validUser) {
                // 构建用户数据（模拟不同权限的用户）
                const userData = {
                    username: values.username,
                    password: values.password, // 实际项目中不应该保存明文密码
                    loginTime: new Date().toISOString(),
                    avatar: null,
                    email: `${values.username}@sjly.com`,
                    // 模拟不同用户的角色和权限
                    roles: values.username === 'sjly' ? ['admin'] : ['operator'],
                    permissions: values.username === 'sjly'
                        ? ['sample:read', 'sample:write', 'device:read', 'device:write', 'data:read', 'data:write', 'demo:access']
                        : ['sample:read', 'data:read'], // demo用户只有基础权限
                    isAdmin: values.username === 'sjly'
                };

                // 使用AuthContext登录
                login(userData, values.remember);

                showMessage('success', '登录成功！欢迎使用 Tree Admin 系统');
                navigate('/dashboard');
            } else {
                showMessage('error', '用户名或密码错误，请检查后重试');
            }
        } catch (error) {
            showMessage('error', '登录失败，请稍后再试');
        } finally {
            setLoading(false);
        }
    };

    // 快速填入默认账号
    const handleUseDefaultAccount = () => {
        form.setFieldsValue({
            username: DEFAULT_CREDENTIALS.username,
            password: DEFAULT_CREDENTIALS.password,
            remember: true
        });
        showMessage('info', '已填入默认账号信息');
    };

    // 第三方登录
    const handleThirdPartyLogin = (platform) => {
        showMessage('info', `${platform} 登录功能开发中...`);
    };

    return (
        <>
            {/* 动画背景样式 */}
            <style>
                {`
          @keyframes gradientFlow {
            0%, 100% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
          }
          
          @keyframes particleFloat {
            0%, 100% { transform: translateY(0px) rotate(0deg); opacity: 0.6; }
            33% { transform: translateY(-20px) rotate(120deg); opacity: 1; }
            66% { transform: translateY(10px) rotate(240deg); opacity: 0.8; }
          }
          
          @keyframes cardSlideIn {
            from { 
              opacity: 0; 
              transform: translateY(40px) scale(0.9); 
            }
            to { 
              opacity: 1; 
              transform: translateY(0px) scale(1); 
            }
          }
          
          @keyframes logoGlow {
            0%, 100% { text-shadow: 0 0 20px rgba(99, 102, 241, 0.3), 0 0 40px rgba(99, 102, 241, 0.2); }
            50% { text-shadow: 0 0 30px rgba(139, 92, 246, 0.5), 0 0 60px rgba(139, 92, 246, 0.3); }
          }
          
          @keyframes ripple {
            0% { transform: scale(1); opacity: 0.8; }
            100% { transform: scale(1.2); opacity: 0; }
          }
          
          .login-bg {
            background: linear-gradient(-45deg, #8b9bf2, #9a7db8, #7c7ff5, #a478fc);
            background-size: 400% 400%;
            animation: gradientFlow 8s ease infinite;
          }
          
          .login-card {
            animation: cardSlideIn 0.8s ease-out;
          }
          
          .logo-glow {
            animation: logoGlow 3s ease-in-out infinite;
          }
          
          .floating-particle {
            position: absolute;
            width: 6px;
            height: 6px;
            background: rgba(255, 255, 255, 0.8);
            border-radius: 50%;
            animation: particleFloat 4s ease-in-out infinite;
            pointer-events: none;
          }
          
          .ripple-effect {
            position: absolute;
            border: 2px solid rgba(255, 255, 255, 0.6);
            border-radius: 50%;
            animation: ripple 2s ease-out infinite;
          }
          
          .glass-morphism {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(20px);
            border: 1px solid rgba(255, 255, 255, 0.2);
          }
          
          .input-glow:focus {
            box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.3), 0 0 20px rgba(99, 102, 241, 0.2) !important;
          }
          
          .btn-shimmer {
            background: linear-gradient(-45deg, #6366f1, #8b5cf6, #6366f1, #8b5cf6);
            background-size: 400% 400%;
            animation: gradientFlow 3s ease infinite;
          }
        `}
            </style>

            <div className="login-bg" style={{
                minHeight: '100vh',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                padding: '20px',
                position: 'relative',
                overflow: 'hidden'
            }}>
                {/* 背景装饰粒子 */}
                {Array.from({ length: 12 }).map((_, i) => (
                    <div
                        key={`particle-${i}`}
                        className="floating-particle"
                        style={{
                            top: `${Math.random() * 100}%`,
                            left: `${Math.random() * 100}%`,
                            animationDelay: `${Math.random() * 4}s`,
                            animationDuration: `${3 + Math.random() * 2}s`
                        }}
                    />
                ))}

                {/* 波纹效果 */}
                <div className="ripple-effect" style={{
                    top: '20%',
                    left: '15%',
                    width: 100,
                    height: 100,
                    animationDelay: '0s'
                }} />
                <div className="ripple-effect" style={{
                    top: '60%',
                    right: '20%',
                    width: 80,
                    height: 80,
                    animationDelay: '1s'
                }} />

                <Card
                    className="login-card glass-morphism"
                    style={{
                        width: '100%',
                        maxWidth: 420,
                        borderRadius: 24,
                        border: 'none',
                        boxShadow: '0 32px 64px rgba(0, 0, 0, 0.15), 0 0 0 1px rgba(255, 255, 255, 0.1)',
                        position: 'relative',
                        overflow: 'hidden'
                    }}
                >
                    {/* 顶部装饰渐变条 */}
                    <div style={{
                        position: 'absolute',
                        top: 0,
                        left: 0,
                        right: 0,
                        height: 4,
                        background: 'linear-gradient(90deg, #8b9bf2, #a478fc, #5dd5f0, #4ade80)',
                        backgroundSize: '200% 100%',
                        animation: 'gradientFlow 3s ease infinite'
                    }} />

                    <div style={{ padding: '40px 32px' }}>
                        {/* Logo和标题 */}
                        <div style={{ textAlign: 'center', marginBottom: 40 }}>
                            <Title level={1} className="logo-glow" style={{
                                margin: '0 0 8px 0',
                                fontSize: 36,
                                fontWeight: 800,
                                background: 'linear-gradient(135deg, #ffffff, #f8fafc)',
                                WebkitBackgroundClip: 'text',
                                WebkitTextFillColor: 'transparent',
                                backgroundClip: 'text'
                            }}>
                                Tree Admin
                            </Title>
                            <Text style={{
                                color: 'rgba(255, 255, 255, 0.8)',
                                fontSize: 16,
                                fontWeight: 500
                            }}>
                                欢迎回来，请登录您的账户
                            </Text>
                        </div>

                        {/* 登录表单 */}
                        <Form
                            form={form}
                            name="login"
                            onFinish={handleLogin}
                            layout="vertical"
                            size="large"
                            autoComplete="off"
                        >
                            <Form.Item
                                name="username"
                                rules={[
                                    { required: true, message: '请输入用户名或邮箱' },
                                    { min: 3, message: '用户名至少3个字符' }
                                ]}
                            >
                                <Input
                                    prefix={<UserOutlined style={{ color: 'rgba(255, 255, 255, 0.6)' }} />}
                                    placeholder="用户名 / 邮箱"
                                    className="input-glow"
                                    style={{
                                        height: 50,
                                        borderRadius: 12,
                                        background: 'rgba(255, 255, 255, 0.1)',
                                        border: '1px solid rgba(255, 255, 255, 0.2)',
                                        color: '#ffffff',
                                        fontSize: 16
                                    }}
                                />
                            </Form.Item>

                            <Form.Item
                                name="password"
                                rules={[
                                    { required: true, message: '请输入密码' },
                                    { min: 6, message: '密码至少6个字符' }
                                ]}
                            >
                                <Input.Password
                                    prefix={<LockOutlined style={{ color: 'rgba(255, 255, 255, 0.6)' }} />}
                                    placeholder="密码"
                                    className="input-glow"
                                    iconRender={(visible) => visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />}
                                    style={{
                                        height: 50,
                                        borderRadius: 12,
                                        background: 'rgba(255, 255, 255, 0.1)',
                                        border: '1px solid rgba(255, 255, 255, 0.2)',
                                        color: '#ffffff',
                                        fontSize: 16
                                    }}
                                />
                            </Form.Item>

                            {/* 记住密码和忘记密码 */}
                            <div style={{
                                display: 'flex',
                                justifyContent: 'space-between',
                                alignItems: 'center',
                                marginBottom: 24
                            }}>
                                <Form.Item name="remember" valuePropName="checked" style={{ margin: 0 }}>
                                    <Checkbox style={{ color: 'rgba(255, 255, 255, 0.8)' }}>
                                        记住密码
                                    </Checkbox>
                                </Form.Item>
                                <Link style={{ color: 'rgba(255, 255, 255, 0.8)' }}>
                                    忘记密码？
                                </Link>
                            </div>

                            {/* 登录按钮 */}
                            <Form.Item style={{ marginBottom: 24 }}>
                                <Button
                                    type="primary"
                                    htmlType="submit"
                                    loading={loading}
                                    className="btn-shimmer"
                                    style={{
                                        width: '100%',
                                        height: 50,
                                        borderRadius: 12,
                                        fontSize: 16,
                                        fontWeight: 600,
                                        border: 'none',
                                        boxShadow: '0 8px 32px rgba(99, 102, 241, 0.4)',
                                        transition: 'all 0.3s ease'
                                    }}
                                    onMouseEnter={(e) => {
                                        e.target.style.transform = 'translateY(-2px)';
                                        e.target.style.boxShadow = '0 12px 48px rgba(99, 102, 241, 0.5)';
                                    }}
                                    onMouseLeave={(e) => {
                                        e.target.style.transform = 'translateY(0px)';
                                        e.target.style.boxShadow = '0 8px 32px rgba(99, 102, 241, 0.4)';
                                    }}
                                >
                                    立即登录
                                </Button>
                            </Form.Item>
                        </Form>

                        {/* 分割线 */}
                        <Divider style={{
                            borderColor: 'rgba(255, 255, 255, 0.2)',
                            margin: '32px 0'
                        }}>
                            <Text style={{ color: 'rgba(255, 255, 255, 0.6)' }}>
                                或者使用第三方登录
                            </Text>
                        </Divider>

                        {/* 第三方登录 */}
                        <Space size="large" style={{ width: '100%', justifyContent: 'center' }}>
                            {[
                                { icon: <GithubOutlined />, name: 'GitHub', color: '#333' },
                                { icon: <GoogleOutlined />, name: 'Google', color: '#4285f4' },
                                { icon: <WechatOutlined />, name: '微信', color: '#1aad19' }
                            ].map((platform) => (
                                <Button
                                    key={platform.name}
                                    shape="circle"
                                    size="large"
                                    onClick={() => handleThirdPartyLogin(platform.name)}
                                    style={{
                                        width: 48,
                                        height: 48,
                                        background: 'rgba(255, 255, 255, 0.1)',
                                        border: '1px solid rgba(255, 255, 255, 0.2)',
                                        color: '#ffffff',
                                        fontSize: 20,
                                        transition: 'all 0.3s ease'
                                    }}
                                    onMouseEnter={(e) => {
                                        e.target.style.background = platform.color;
                                        e.target.style.transform = 'scale(1.1)';
                                        e.target.style.boxShadow = `0 8px 25px ${platform.color}40`;
                                    }}
                                    onMouseLeave={(e) => {
                                        e.target.style.background = 'rgba(255, 255, 255, 0.1)';
                                        e.target.style.transform = 'scale(1)';
                                        e.target.style.boxShadow = 'none';
                                    }}
                                >
                                    {platform.icon}
                                </Button>
                            ))}
                        </Space>

                        {/* 注册链接 */}
                        <div style={{ textAlign: 'center', marginTop: 32 }}>
                            <Text style={{ color: 'rgba(255, 255, 255, 0.6)' }}>
                                还没有账户？{' '}
                                <Link style={{ color: '#ffffff', fontWeight: 600 }}>
                                    立即注册
                                </Link>
                            </Text>
                        </div>
                    </div>
                </Card>
            </div>
        </>
    );
};

export default Login;
